package com.im.controller;

import com.alibaba.fastjson.JSONObject;
import com.im.annotation.Jwt;
import com.im.dao.UserDao;
import com.im.pojo.*;
import com.im.pojoClass.ImLatelyList;
import com.im.pojoClass.Result;
import com.im.pojoClass.ResultCode;
import com.im.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author 13349
 */
@Api(tags = {"好友"}, value = "FriendController")
@RestController
@RequestMapping("/friend")
@CrossOrigin
public class FriendController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Jwt
    @ApiOperation(value = "发送好友申请", notes = "返回是否发送成功提示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "send_id", value = "发送方id"),
            @ApiImplicitParam(name = "receive_id", value = "接收方id")
    })
    @RequestMapping(value = "/addUserApply", method = RequestMethod.POST)
    public Result addUserApply(@RequestParam(value = "send_id") String send_id,
                               @RequestParam(value = "receive_id") String receive_id) {

        // 判断用户是否存在
        ImUser nameExist1 = userDao.selectUser(send_id);
        ImUser nameExist2 = userDao.selectUser(receive_id);
        if (nameExist1 == null || nameExist2 == null) {
            // {code:500,msg:"用户不存在"}
            return new Result(ResultCode.FAILED, "用户不存在");
        }

        // 不允许加自己为好友
        if (send_id.equals(receive_id)) {
            // {code:500,msg:"不能加自己为好友"}
            return new Result(ResultCode.FAILED, "不能加自己为好友");
        }

        // 查询是否已经是好友
        ImLately selectLately = userDao.selectLately(send_id, receive_id);
        if (selectLately != null) {
            // {code:500,msg:"你们已经是好友"}
            return new Result(ResultCode.FAILED, "你们已经是好友");
        }

        // 查询是否发送过好友申请
        ImApply selectUserApplyYesAgree = userDao.selectUserApplyAgree(send_id, receive_id);
        if (selectUserApplyYesAgree != null) {
            // {code:500,msg:"等待对方同意"}
            return new Result(ResultCode.FAILED, "等待对方同意");
        }

        // 添加好友申请表
        ImApply imApply = new ImApply();
        imApply.setSend_id(send_id);
        imApply.setReceive_id(receive_id);
        imApply.setAgree(0);
        userDao.insertApply(imApply);

        // 判断是否在线
        Boolean user_login = redisTemplate.opsForSet().isMember("userLogin", receive_id);
        // 不在线
        if (!user_login) {
            return new Result(ResultCode.SUCCESS, "好友请求发送成功");
        }

        // 序列化
        HashMap<String, String> hashMap = new HashMap<>(4);
        hashMap.put("send_id", send_id);
        hashMap.put("receive_id", receive_id);

        ImMq imMq = new ImMq();
        imMq.setCode("201");
        imMq.setData(hashMap);

        String s = JSONObject.toJSONString(imMq);

        // 通过RabbitMQ发送
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean b, String s) {
//                if (b) {
//                    System.out.println("发送成功");
//                } else {
//                    System.out.println("错误原因" + s);
//                }
//            }
//        });
        rabbitTemplate.convertAndSend("im_exchange", "", s);

        return new Result(ResultCode.SUCCESS, "好友请求发送成功");
    }

    /************************************************************************************************/
    @Jwt
    @ApiOperation(value = "同意添加好友", notes = "receive_id同意send_id的好友请求")
    @RequestMapping(value = "/agreeUserApply", method = RequestMethod.POST)
    public Result agreeUserApply(@RequestParam String send_id, @RequestParam String receive_id) {
//        System.out.println(send_id);
//        System.out.println(receive_id);
        // UUID
        String uuid = UUID.randomUUID().toString();
        // 时间戳
        String time = String.valueOf(System.currentTimeMillis());

        // 添加消息
        ImMessage imMessage = new ImMessage(uuid, "你们已经成为了好友", "text", time);
        userDao.insertMessage(imMessage);

        // 添加一条最近联系人
        ImLately imLately1 = new ImLately(send_id, receive_id, uuid, 0);
        ImLately imLately2 = new ImLately(receive_id, send_id, uuid, 0);
        userDao.insertLately(imLately1);
        userDao.insertLately(imLately2);

        // 修改申请通过标志
        ImApply imApply = new ImApply(send_id, receive_id, 1);
        userDao.updateApplyAgree(imApply);

        // 判断是否在线
        Boolean user_login = redisTemplate.opsForSet().isMember("userLogin", send_id);
//        System.out.println(user_login);
        // 不在线
        if (!user_login) {
            return new Result(ResultCode.SUCCESS);
        }

        // 序列化
        HashMap<String, String> hashMap = new HashMap<>(4);
        hashMap.put("send_id", send_id);
        hashMap.put("receive_id", receive_id);

        ImMq imMq = new ImMq();
        imMq.setCode("203");
        imMq.setData(hashMap);

        String s = JSONObject.toJSONString(imMq);

        // 通过RabbitMQ发送
        rabbitTemplate.convertAndSend("im_exchange", "", s);

        return new Result(ResultCode.SUCCESS);
    }

    @Jwt
    @ApiOperation(value = "获取最近好友列表", notes = "返回最近联系人列表")
    @RequestMapping(value = "/selectLatelyList", method = RequestMethod.POST)
    public Result selectLatelyList(@RequestParam String user_id) {

        // 从Redis获取
        HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash();
        List<String> values = opsForHash.values("im_lately" + user_id);

        if (values.size() != 0) {
            List<ImLatelyList> collect = values.stream().map(x -> JSONObject.parseObject(x, ImLatelyList.class)).collect(Collectors.toList());
            return new Result(ResultCode.SUCCESS, collect);
        }

        // Redis为空，从数据库获取
        List<ImLatelyList> selectLatelyList = userDao.selectLatelyList(user_id);
        return new Result(ResultCode.SUCCESS, selectLatelyList);
    }


    @Jwt
    @ApiOperation(value = "好友未读归0", notes = "返回是否成功提示")
    @RequestMapping(value = "/updateLatelyReadZero", method = RequestMethod.POST)
    public Result updateLatelyReadZero(@RequestParam String send_id, @RequestParam String receive_id) {
        // 创建ImLately对象
        ImLately imLately = new ImLately(send_id, receive_id, null, 0);

        // 未读数归0
        Integer updateLatelyRead = userDao.updateLatelyRead(imLately);
        if (updateLatelyRead > 0) {
            return new Result(ResultCode.SUCCESS);
        }

        return new Result(ResultCode.FAILED, "操作失败");
    }

    @Jwt
    @ApiOperation(value = "查看好友申请列表")
    @RequestMapping(value = "/selectUserApplyList", method = RequestMethod.POST)
    public Result selectUserApplyList(@RequestParam String user_id) {
        // 从Redis获取
        HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash();
        List<String> values = opsForHash.values("im_apply" + user_id);

        if (values.size() != 0) {
            List<ImUser> collect = values.stream().map(x -> JSONObject.parseObject(x, ImUser.class)).collect(Collectors.toList());
            return new Result(ResultCode.SUCCESS, collect);
        }

        List<ImUser> imUserApplyNotAgreeList = userDao.selectUserApplyNotAgreeList(user_id);
        return new Result(ResultCode.SUCCESS, imUserApplyNotAgreeList);
    }

}
